﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Model;

namespace PlatformClient
{
    public partial class TeacherUserForm : DevExpress.XtraEditors.XtraForm
    {
        public TeacherUserForm()
        {
            InitializeComponent();
        }


        private Thread _thread;
        private bool _isLoad;
     

        private void TeacherUserForm_Load(object sender, EventArgs e)
        {
             
            _isLoad = true;
            _thread = new Thread(BindGrid);
            _thread.Start();
        }

        private void BindControlData()
        {
            DataSet dsCompany = new DataSet();

            if (MainForm.MyUserInfo.CompanyName == Common.ConstParameters.MainCompanyName)
            {
                dsCompany = MainForm.PositionService.CompanyGetList("");

            }
            else
            {
                dsCompany = MainForm.PositionService.CompanyGetList(
                    "CompanyName like '" + MainForm.MyUserInfo.CompanyName
                    + "%'");
            }
            if (dsCompany != null && dsCompany.Tables.Count > 0)
            {
                foreach (DataRow row in dsCompany.Tables[0].Rows)
                {
                    string id = row["Id"].ToString();
                    string name = row["CompanyName"].ToString();
                    ImageComboBoxItem item = new ImageComboBoxItem();
                    item.Description = name;
                    item.Value = id;
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        comboBoxEdit_company.Properties.Items.Add(item);                       
                    }));
                }
            }

        }


        private void BindGrid()
        {
            try
            {
                string strType = radioGroup_type.Properties.Items[radioGroup_type.SelectedIndex].Value.ToString();
                string strValue = textEdit_String.Text.Trim();

                StringBuilder strWhere = new StringBuilder();
                if (strValue.Trim() != "")
                {
                    strWhere.Append(strType);
                    strWhere.Append(" like '%");
                    strWhere.Append(strValue);
                    strWhere.Append("%' ");
                }
                if (MainForm.MyUserInfo.CompanyName != Common.ConstParameters.MainCompanyName)
                {
                    if (strWhere.ToString() != "")
                    {
                        strWhere.Append(" and ");
                    }
                    strWhere.Append(" CompanyName = '");
                    strWhere.Append(MainForm.MyUserInfo.CompanyName);
                    strWhere.Append("'");

                }


                DataSet ds = new DataSet();                            
                ds = MainForm.PositionService.GetListOfTeacher(strWhere.ToString());


                if (ds != null && ds.Tables.Count == 1)
                {
                    ClearInputControl();

                   
                    BeginInvoke(new MethodInvoker(() =>
                    {

                        gridControl1.DataSource = ds.Tables[0];
                        gridView1.GroupPanelText = "共" + ds.Tables[0].Rows.Count + "条数据";
                       
                            gridView1.FocusedRowHandle = gridView1.RowCount - 1;
             
                        btn_select.Enabled = true;


                        if (_isLoad)
                        {
                            BindControlData();
                            _isLoad = false;
                        }

                    }));
                }

            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
                //  BeginInvoke(new MethodInvoker(() => btn_select.Enabled = true));               
            }
        }


        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);//
            if (row != null)
            {
                label_id.Text = row["id"].ToString();
 
                txtEdt_PhoneNumber.Text = row["PhoneNumber"].ToString();
                textEdit_Imei.Text = row["IMEI"].ToString();
                textEdit_Name.Text = row["Name"].ToString();
                comboBoxEdit_company.Text = row["CompanyId"].ToString();
            
                btn_modify.Enabled = true;
                 
            }
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);//
            if (row != null)
            {
                label_id.Text = row["id"].ToString();
                txtEdt_PhoneNumber.Text = row["PhoneNumber"].ToString();
                textEdit_Imei.Text = row["IMEI"].ToString();
                textEdit_Name.Text = row["Name"].ToString();
                comboBoxEdit_company.Text = row["CompanyId"].ToString();
                btn_modify.Enabled = true; 

            }
        }


        private void simpleButton_add_Click(object sender, EventArgs e)
        {
            if (btn_add.Tag.ToString() == "新增")
            {
                label_id.Text = "";
                textEdit_Name.Text = "";
              
                txtEdt_PhoneNumber.Text = "";
                textEdit_Imei.Text = "";
              

                txtEdt_PhoneNumber.Enabled = true;
                textEdit_Imei.Enabled = true;
                textEdit_Name.Enabled = true;
                comboBoxEdit_company.Enabled = true;

                gridControl1.Enabled = false;
                btn_select.Enabled = false;
                btn_modify.Visible = false;
                btn_delete.Visible = false;
                btn_cancel.Visible = true;
                btn_cancel.Location = btn_modify.Location;
                btn_add.Tag = "保存";
                btn_add.Image = Properties.Resources.UserForm_btnsave001;
            }
            else
            {
                if (!CheckInput()) return;

                string strPhoneNum = txtEdt_PhoneNumber.Text.Trim();
                string strImei = textEdit_Imei.Text.Trim();
                string strName = textEdit_Name.Text;

                if (MainForm.PositionService.ParentExists(strPhoneNum))
                {
                    XtraMessageBox.Show("该号码已存在，请核对！");
                    return;
                }

                int companyId = int.Parse(comboBoxEdit_company.Properties.Items[
               comboBoxEdit_company.SelectedIndex].Value.ToString());

                try
                {
                    ParentInfo model = new ParentInfo
                    {
                        PhoneNumber = strPhoneNum,                         
                        Imei = strImei,
                        Name = strName,
                        CompanyId =  companyId,
                        RegistTime = DateTime.Now,
                        LastLoginTime = DateTime.Now
                    };
                    if (MainForm.PositionService.ParentAdd(model))
                    {
                        XtraMessageBox.Show("添加成功");
                        gridControl1.Enabled = true;
                        btn_select.Enabled = true;
                        btn_delete.Visible = true;
                        btn_modify.Visible = true;
                        btn_cancel.Visible = false;

                        comboBoxEdit_company.Enabled = false;
                        txtEdt_PhoneNumber.Enabled = false;
                        textEdit_Imei.Enabled = false;
                        textEdit_Name.Enabled = false;
                    
                        

                        btn_add.Tag = "新增";
                        btn_add.Image = Properties.Resources.UserForm_btnadd001;
                       
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("添加失败");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }


                //taxi.TaxiType=
            }

        }

        private void simpleButton_modify_Click(object sender, EventArgs e)
        {
            if (label_id.Text == string.Empty)
            {
                XtraMessageBox.Show("请选择要修改的出租车！");
                return;
            }
            if (btn_modify.Tag.ToString() == "修改")
            {
                txtEdt_PhoneNumber.Enabled = true;
                textEdit_Imei.Enabled = true;
                textEdit_Name.Enabled = true;
                comboBoxEdit_company.Enabled = true;


                gridControl1.Enabled = false;
                btn_select.Enabled = false;
                btn_delete.Visible = false;
                btn_cancel.Visible = true;
                btn_cancel.Location = btn_modify.Location;
                btn_modify.Location = btn_add.Location;
                btn_add.Visible = false;
                btn_modify.Tag = "保存";
                btn_modify.Image = Properties.Resources.UserForm_btnsave001;
            }
            else
            {
                if (!CheckInput()) return;
                int id = int.Parse(label_id.Text);
                string strPhoneNum = txtEdt_PhoneNumber.Text.Trim();
                string strImei = textEdit_Imei.Text.Trim();
                string strName = textEdit_Name.Text;
                int companyId = int.Parse(comboBoxEdit_company.Properties.Items[
                comboBoxEdit_company.SelectedIndex].Value.ToString());
                  
                ParentInfo model = new ParentInfo
                {
                    Id = id,
                    PhoneNumber = strPhoneNum,
                    Imei = strImei,
                    Name = strName,
                    CompanyId = companyId
                };
                try
                {
                    if (MainForm.PositionService.ParentUpdate(model))
                    {
                        XtraMessageBox.Show("修改成功！");

                        gridControl1.Enabled = true;
                        btn_select.Enabled = true;
                        btn_delete.Visible = true;
                        btn_add.Visible = true;
                        btn_modify.Location = btn_cancel.Location;
                        btn_cancel.Visible = false;
                        btn_modify.Tag = "修改";
                        btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
                        
                        comboBoxEdit_company.Enabled = false;
                        txtEdt_PhoneNumber.Enabled = false;
                        textEdit_Imei.Enabled = false;
                        textEdit_Name.Enabled = false;
                   


                        btn_add.Enabled = false;

                        //BindGrid();
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("修改失败！");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                    return;
                }
            }
        }

        private void simpleButton_delete_Click(object sender, EventArgs e)
        {
            DataRow row = this.gridView1.GetDataRow(this.gridView1.FocusedRowHandle);
            string id;
            if (row == null)
            {
                XtraMessageBox.Show("请选择要删除的车辆！");
                return;
            }
            id = row["id"].ToString();
            string phoneNum = row["PhoneNumber"].ToString();
            if (XtraMessageBox.Show("确认删除手机号为【" + phoneNum
                + "】的家长吗？", "警告", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                try
                {
                    if (MainForm.PositionService.ParentDelete(int.Parse(id)))
                    {
                        XtraMessageBox.Show("删除成功！");
                        _thread = new Thread(BindGrid);
                        _thread.Start();
                    }
                    else
                    {
                        XtraMessageBox.Show("删除失败！");
                    }
                }
                catch (Exception ex)
                {
                    Common.CommonRoutine.HandlingExceptions(ex, true);
                }

            }
        }

        private void simpleButton_Select_Click(object sender, EventArgs e)
        {
            gridView1.GroupPanelText = "数据加载中...";
            btn_select.Enabled = false;
            _thread = new Thread(BindGrid);
            _thread.Start();
        }

        private void simpleButton_cancle_Click(object sender, EventArgs e)
        {
            gridView1_RowClick(null, null);
            gridControl1.Enabled = true;
            btn_select.Enabled = true;
            btn_delete.Visible = true;
            btn_cancel.Visible = false;
            btn_add.Visible = true;
            btn_add.Tag = "新增";
            btn_add.Image = Properties.Resources.UserForm_btnadd001;
            btn_modify.Visible = true;
            btn_modify.Tag = "修改";
            btn_modify.Image = Properties.Resources.UserForm_btnmodify001;
            btn_modify.Location = btn_cancel.Location;
             
            txtEdt_PhoneNumber.Enabled = false;
            textEdit_Imei.Enabled = false;
            textEdit_Name.Enabled = false;
            comboBoxEdit_company.Enabled = false;

        }

        public void ClearInputControl()
        {
            BeginInvoke(new MethodInvoker(() =>
            {
                label_id.Text = "";
                textEdit_Name.Text = "";

                comboBoxEdit_company.SelectedIndex = -1;
                txtEdt_PhoneNumber.Text = "";
                textEdit_Imei.Text = "";
              
            }));
        }

        private bool CheckInput()
        {

            string strPhoneNum = txtEdt_PhoneNumber.Text.Trim();
            string strImei = textEdit_Imei.Text.Trim();
            string strName = textEdit_Name.Text;
          
          
        
            if (strPhoneNum == string.Empty)
            {
                XtraMessageBox.Show("出租车手机号码不能为空");
                txtEdt_PhoneNumber.Focus();
                return false;
            }
            if (strImei.Length > 20)
            {
                XtraMessageBox.Show("IMEI号码输入长度过大！");
                textEdit_Imei.Focus();
                return false;
            }
            if (Encoding.GetEncoding("GBK").GetBytes(strName).Length > 10)
            {
                XtraMessageBox.Show("教师姓名长度太长！");
                textEdit_Name.Focus();
                return false;
            }
            if (comboBoxEdit_company.SelectedIndex < 0
            || comboBoxEdit_company.Text == "")
            {
                XtraMessageBox.Show("请选择所属公司");
                comboBoxEdit_company.Focus();
                return false;
            }
            
             
          
            return true;
        }

        #region  窗体控件操作、效果
        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;

            Cursor = Cursors.Arrow;

        }

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }
        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Default;
        }
        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }

        #endregion

        //private void btn_exportToExcel_Click(object sender, EventArgs e)
        //{
        //    saveFileDialog1.FileName = "车辆列表";
        //    saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
        //    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        //    {
        //        gridView1.ExportToXls(saveFileDialog1.FileName);
        //        XtraMessageBox.Show("Excel导出完成！");
        //    }
        //}

        private void From_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_thread != null)
            {
                _thread.Abort();
            }
        }



        private void textEdit_condition_KeyPress(object sender, KeyPressEventArgs e)
        {

            if ((Keys)e.KeyChar == Keys.Enter)
            {
                simpleButton_Select_Click(null, null);
            }

        }

 


    }
}